const { execSync } = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");

const pnpmOutput = execSync("pnpm ls --depth Infinity --parseable", {
  encoding: "utf8",
});
const dependencyPaths = pnpmOutput.trim().split("\n").slice(1);
const licenseNames = [
  "LICENSE-MIT.txt",
  "license-MIT.txt",
  "LICENSE-MIT",
  "license-MIT",
  "LICENSE.BSD",
  "UNLICENSE",
  "unlicense",
  "LICENSE.md",
  "license.md",
  "LICENSE.txt",
  "license.txt",
  "LICENCE",
  "licence",
  "LICENSE",
  "license",
  "License",
];
const outputFile = "license-disclaimer.adoc";

fs.writeFileSync(
  outputFile,
  `= 开源组件许可声明
:toc:

`,
);

for (const depPath of dependencyPaths) {
  try {
    const packageJsonPath = path.join(depPath, "package.json");
    if (!fs.existsSync(packageJsonPath)) continue;
    const { name, version, license } = JSON.parse(
      fs.readFileSync(packageJsonPath, "utf8"),
    );

    let licenseContent = "";
    for (const licenseName of licenseNames) {
      if (!licenseContent) {
        const licensePath = path.join(depPath, licenseName);
        if (fs.existsSync(licensePath)) {
          licenseContent = fs.readFileSync(licensePath, "utf8");
        }
      }
    }

    if (!licenseContent && license) {
      console.log(`${name}@${version} no Disclaimer`);
      licenseContent = `(未找到许可声明，但标明使用 ${license} 许可证)`;
    } else if (!licenseContent && !license) {
      console.log(`${name}@${version} no LICENSE`);
      licenseContent = `(未找到许可信息)`;
    }

    const content = `== https://www.npmjs.com/package/${name}/v/${version}[${name}@${version}]

....
${licenseContent}
....

`;
    fs.appendFileSync(outputFile, content);
  } catch (error) {
    console.error(`Error processing ${depPath}:`, error.message);
  }
}

console.log("Disclaimer file generated successfully!");
